package cn.scw.project.facility.service.impl;

import cn.scw.common.constant.DictTypeConsts;
import cn.scw.common.constant.FacConsts;
import cn.scw.common.exception.CustomException;
import cn.scw.common.utils.DateUtils;
import cn.scw.common.utils.RegexUtils;
import cn.scw.common.utils.SecurityUtils;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.bean.ToolUtils;
import cn.scw.common.utils.sql.JpaUtil;
import cn.scw.common.utils.sql.SqlUtil;
import cn.scw.framework.aspectj.lang.annotation.DataScope;
import cn.scw.framework.web.page.PageDomain;
import cn.scw.framework.web.page.TableSupport;
import cn.scw.project.facility.domain.FacFacility;
import cn.scw.project.facility.domain.netework.bean.FacFacilityAddReq;
import cn.scw.project.facility.domain.netework.bean.FacFacilityAutoAddReq;
import cn.scw.project.facility.domain.netework.bean.FacFacilityListReq;
import cn.scw.project.facility.domain.vo.FacFacilityVo;
import cn.scw.project.facility.mapper.FacFacilityMapper;
import cn.scw.project.facility.service.IFacFacilityService;
import cn.scw.project.goods.service.IGAreaService;
import cn.scw.project.system.domain.SysDealer;
import cn.scw.project.system.domain.SysUser;
import cn.scw.project.system.service.ISysDealerService;
import cn.scw.project.system.service.ISysDictDataService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 设备Service业务层处理
 *
 * @author api
 * @date 2020-05-20
 */
@Service
public class FacFacilityServiceImpl implements IFacFacilityService {
    @Autowired
    private FacFacilityMapper facFacilityMapper;
    @Autowired
    private IGAreaService igAreaService;
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private ISysDealerService iSysDealerService;

    /**
     * 查询设备
     *
     * @param id 设备ID
     * @return 设备
     */
    @Override
    public FacFacility selectFacFacilityById(Long id) {
        return facFacilityMapper.selectFacFacilityById(id);
    }

    @Override
    public FacFacilityVo selectFacFacilityVoById(Long id) {
        return facFacilityMapper.selectFacFacilityVoById(id);
    }

    @Override
    public FacFacility selectFacFacilityByCode(String code) {
        return facFacilityMapper.selectFacFacilityByCode(code);
    }

    @Override
    public FacFacilityVo selectFacFacilityVoByCode(String code) {
        return facFacilityMapper.selectFacFacilityVoByCode(code);
    }

    /**
     * 查询设备列表
     *
     * @param req 设备
     * @return 设备
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FacFacilityVo> selectFacFacilityList(FacFacilityListReq req) {
        req.setPositionDetails(JpaUtil.getNullOrLikeStr(req.getPositionDetails()));
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDealer dealer = iSysDealerService.selectSysDealerByUserId(user.getUserId());
        if (dealer != null)
            req.setDealerId(dealer.getId());
        startPage();
        return facFacilityMapper.selectFacFacilityList(req);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FacFacilityVo> queryFacFacilityList(FacFacilityListReq req) {
        return facFacilityMapper.selectFacFacilityList(req);
    }

    private void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }


    /**
     * 新增设备
     *
     * @param req 设备
     * @return 结果
     */
    @Override
    public int insertFacFacility(FacFacilityAddReq req) {
        if (StringUtils.isBlank(req.getLitimgUrl()))
            throw new CustomException("请选择缩略图");
        if (StringUtils.isBlank(req.getCode()))
            throw new CustomException("请输入设备编码");
        if (this.existsByCode(req.getCode()))
            throw new CustomException("设备编码已存在");
        if (StringUtils.isBlank(req.getName()))
            throw new CustomException("请输入设备名称");
        if (StringUtils.isAnyBlank(req.getPositionProvince(), req.getPositionCity(), req.getPositionArea(), req.getPositionDetails()))
            throw new CustomException("请填写设备安装位置");
//        if (igAreaService.existsByCode(req.getPositionProvince()))
//            throw new CustomException("请选择正确的位置");
//        if (igAreaService.existsByCode(req.getPositionCity()))
//            throw new CustomException("请选择正确的位置");
//        if (igAreaService.existsByCode(req.getPositionArea()))
//            throw new CustomException("请选择正确的位置");
        if (StringUtils.isBlank(req.getLeader()))
            throw new CustomException("请填写设备负责人");
        if (StringUtils.isBlank(req.getLeaderPhone()))
            throw new CustomException("请填写负责人电话号码");
        if (!RegexUtils.isPhone(req.getLeaderPhone()))
            throw new CustomException("请填写正确的电话号码");
        if (StringUtils.isNotBlank(req.getStatus())) {
            if (!iSysDictDataService.existsDictLabel(DictTypeConsts.FAC_FACILITY_STATUS, req.getStatus()))
                throw new CustomException("请选择正确的设备状态");
        } else {
            req.setStatus(FacConsts.FACILITY_STATUS_NORMAL);
        }

        FacFacility facFacility = new FacFacility();
        ToolUtils.copyPropertiesIgnoreNull(req, facFacility);

        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDealer dealer = iSysDealerService.selectSysDealerByUserId(user.getUserId());
        if (dealer != null){// 经销商操作
            facFacility.setDealerId(dealer.getId());
        }else{
            // 管理员操作

        }


        facFacility.setPutDate(new Date());

//        try {
//            facFacility.setQrCodeUrl(QRCodeUtils.createQRCode(facFacility.getCode()));
//        } catch (Exception e) {
//            throw new CustomException("生成二维码错误");
//        }

        return facFacilityMapper.insertFacFacility(facFacility);
    }

    @Override
    public int autoInsertFacFacility(FacFacilityAutoAddReq req) {
        FacFacility facFacility = new FacFacility();
        ToolUtils.copyPropertiesIgnoreNull(req, facFacility);
        Date rentDate = new Date();
        Date expireDate = DateUtils.addMonth(rentDate, facFacility.getRentMonth());
        facFacility.setRentDate(rentDate);
        facFacility.setExpireDate(expireDate);
        facFacility.setExpire(false);
        facFacility.setStatus(FacConsts.FACILITY_STATUS_OFF);
        return facFacilityMapper.insertFacFacility(facFacility);
    }

    public void autoUpdateIsExpire() {
        facFacilityMapper.autoUpdateIsExpire();
    }

    /**
     * 修改设备
     *
     * @param req 设备
     * @return 结果
     */
    @Override
    public int updateFacFacility(FacFacilityAddReq req) {
        FacFacility facFacility = this.selectFacFacilityById(req.getId());
        if (facFacility == null)
            throw new CustomException("设备不存在");
        if (StringUtils.isNotBlank(req.getCode()) && !req.getCode().equals(facFacility.getCode())) {
            if (this.existsByCode(req.getCode()))
                throw new CustomException("设备编码已存在");
        }

        if (StringUtils.isNotBlank(req.getStatus()) && !req.getStatus().equals(facFacility.getStatus())) {
            if (!iSysDictDataService.existsDictLabel(DictTypeConsts.FAC_FACILITY_STATUS, req.getStatus()))
                throw new CustomException("请选择正确的设备状态");
        }

        ToolUtils.copyPropertiesIgnoreNull(req, facFacility);

//        if (igAreaService.existsByCode(facFacility.getPositionProvince()))
//            throw new CustomException("请选择正确的位置");
//        if (igAreaService.existsByCode(facFacility.getPositionCity()))
//            throw new CustomException("请选择正确的位置");
//        if (igAreaService.existsByCode(req.getPositionArea()))
//            throw new CustomException("请选择正确的位置");
        if (!RegexUtils.isPhone(facFacility.getLeaderPhone()))
            throw new CustomException("请填写正确的电话号码");
        if (facFacility.getPutDate() == null)
            facFacility.setPutDate(new Date());
        return facFacilityMapper.updateFacFacility(facFacility);
    }

    @Override
    public int updateFacFacility(FacFacility facFacility) {
        return facFacilityMapper.updateFacFacility(facFacility);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备ID
     * @return 结果
     */
    @Override
    public int deleteFacFacilityByIds(Long[] ids) {
        return facFacilityMapper.deleteFacFacilityByIds(ids);
    }

    /**
     * 删除设备信息
     *
     * @param id 设备ID
     * @return 结果
     */
    @Override
    public int deleteFacFacilityById(Long id) {
        return facFacilityMapper.deleteFacFacilityById(id);
    }

    @Override
    public boolean existsByCode(String code) {
        return facFacilityMapper.existsByCode(code);
    }

    @Override
    public int countByUser(Long userId) {
        return facFacilityMapper.countByUser(userId);
    }

}
